package cn.baiweigang.uu.api.future;

import cn.baiweigang.uu.api.BaseApi;
import cn.baiweigang.uu.constants.BtcConfig;
import cn.baiweigang.uu.enums.*;
import cn.baiweigang.uu.model.PositionInfo;
import cn.baiweigang.uu.model.TradeInfo;
import cn.baiweigang.uu.msg.MsgPublisher;
import cn.baiweigang.uu.msg.OrderChangeEvent;
import cn.baiweigang.uu.msg.PositionChangeEvent;
import cn.baiweigang.uu.utils.DateUtil;
import cn.baiweigang.uu.utils.LogUtil;
import cn.baiweigang.uu.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.huobi.future.wss.event.OrdersSubResponse;
import com.huobi.future.wss.event.PositionsSubResponse;
import com.huobi.future.wss.handle.WssNotificationHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class FutureNotificationWs extends BaseApi {
    private String host = BtcConfig.HB_HOST;
    private String url = "/notification";

    @Autowired
    private MsgPublisher msgPublisher;

    public boolean sub(String accountName, SymbolEnum symbol) {
        loadByAccountName(accountName);
        WssNotificationHandle wssNotificationHandle = new WssNotificationHandle(host, url,
                apiKeyInfo.getApiKey(), apiKeyInfo.getSecretKey());
        try {
            List<String> channels = Lists.newArrayList();
            channels.add("orders." + symbol.getCode());
            channels.add("positions." + symbol.getCode());
            wssNotificationHandle.sub(channels, response -> {
//                LogUtil.logDebug("收到服务端推送的订单信息 ");
//                LogUtil.logDebug(response);

                if (StringUtil.isNotBlank(response) &&
                        response.indexOf("\"topic\":\"orders.") > 0) {
                    //订单成交信息
                    OrdersSubResponse order = JSON.parseObject(response, OrdersSubResponse.class);
                    TradeInfo tradeInfo = new TradeInfo();
                    tradeInfo.setAccountName(accountName);
                    tradeInfo.setContractType(ContractTypeEnum.byCode(order.getContractType()));
                    tradeInfo.setContractCode(ContractCodeEnum.byCode(order.getContractCode()));
                    tradeInfo.setVolume(order.getVolume().longValue());
                    tradeInfo.setPrice(order.getPrice());
                    tradeInfo.setTradeAvgPrice(order.getTradeAvgPrice());
                    tradeInfo.setIstpsl(order.getIsTpsl());
                    tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(order.getOrderPriceType()));
                    tradeInfo.setDirection(DirectionEnum.byCode(order.getDirection()));
                    tradeInfo.setOffset(OffsetEnum.byCode(order.getOffset()));
                    tradeInfo.setStatus(TradeStatusEnum.byCode(order.getStatus()));
                    tradeInfo.setOrderId(order.getOrderId());
                    tradeInfo.setOrdeIdStr(order.getOrderIdStr());
                    tradeInfo.setClientOrderId(order.getClientOrderId() + "");
                    tradeInfo.setOrderSource(order.getOrderSource());
                    tradeInfo.setCreatedGmt(order.getCreatedAt());
                    tradeInfo.setTradeVolume(order.getTradeVolume());
                    tradeInfo.setTradeTurnover(order.getTradeTurnover());
                    tradeInfo.setFee(order.getFee());
                    tradeInfo.setTradeAvgPrice(order.getTradeAvgPrice());
                    tradeInfo.setMarginFrozen(order.getMarginFrozen());
                    tradeInfo.setProfit(order.getProfit());
                    tradeInfo.setRealProfit(order.getRealProfit());

                    tradeInfo.setDealDateTime(DateUtil.formatDateYMDHMS(new Date(tradeInfo.getCreatedGmt())));

                    OrderChangeEvent orderChangeEvent = new OrderChangeEvent("OrderNotificationWs", tradeInfo);
                    LogUtil.logInfo("交割合约 收到ws发来的订单信息，准备发内部消息");
                    msgPublisher.publish(orderChangeEvent);
                } else if (StringUtil.isNotBlank(response) &&
                        response.indexOf("\"topic\":\"positions.") > 0) {
                    //持仓变化信息
                    PositionsSubResponse positionsSubResponse = JSON.parseObject(response, PositionsSubResponse.class);

                    PositionInfo positionInfo = new PositionInfo();
                    if (positionsSubResponse.getData() != null && positionsSubResponse.getData().size() > 0) {
                        if (positionsSubResponse.getEvent().equalsIgnoreCase("snapshot") ||
                                positionsSubResponse.getEvent().equalsIgnoreCase("init")) {
                            return;
                        }
                        PositionsSubResponse.DataBean dataBean = positionsSubResponse.getData().get(0);
                        positionInfo.setEvent(positionsSubResponse.getEvent());
                        positionInfo.setTs(positionsSubResponse.getTs());
                        positionInfo.setSymbol(SymbolEnum.byCode(dataBean.getSymbol()));
                        positionInfo.setContractType(ContractTypeEnum.byCode(dataBean.getContractType()));
                        positionInfo.setVolume(dataBean.getVolume().intValue());
                        positionInfo.setAvailable(dataBean.getAvailable().intValue());
                        positionInfo.setFrozen(dataBean.getFrozen().intValue());
                        positionInfo.setCostOpen(dataBean.getCostOpen());
                        positionInfo.setCostHold(dataBean.getCostHold());
                        positionInfo.setProfitUnreal(dataBean.getProfitUnreal());
                        positionInfo.setProfitRate(dataBean.getProfitRate());
                        positionInfo.setProfit(dataBean.getProfit());
                        positionInfo.setPositionMargin(dataBean.getPositionMargin());
                        positionInfo.setLeverRate(dataBean.getLeverRate());
                        positionInfo.setDirection(DirectionEnum.byCode(dataBean.getDirection()));
                        positionInfo.setLastPrice(dataBean.getLastPrice());

                        PositionChangeEvent positionChangeEvent = new PositionChangeEvent("FutureNotificationWs", positionInfo);
                        LogUtil.logInfo("交割合约 收到ws发来的持仓变化信息，准备发内部消息");
                        msgPublisher.publish(positionChangeEvent);
                    }
                } else {
//                    LogUtil.logError("topic异常 ");
//                    LogUtil.logError(response);
                }

            });
            return true;
        } catch (Throwable e) {
            LogUtil.logError(e);
        }
        return false;
    }
}
